import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { localStorage } from '@/utils/storage';
import useStore from '@/store';

// 创建 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_API,
	timeout: 50000,
	withCredentials: true, // send cookies when cross-domain requests
	//headers: { 'Content-Type': 'application/json;charset=utf-8' }
}); 

// 请求拦截器
service.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		if (!config.headers) {
			throw new Error(
				`Expected 'config' and 'config.headers' not to be undefined`
			);
		}
		const { user } = useStore();
		if (user.token) {
			config.headers.Authorization = `Bearer ${localStorage.get('token')}`;
		}
		return config;
	},
	error => {
		console.log(error) // for debug
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		if (response.status == 401 || response.status == 403) {
			ElMessage({
				message: "您没权限执行此操作",
				type: 'error',
				duration: 5 * 1000
			})
			return;
		}
		//console.log(response) // for debug
		const res= response.data;		
		
		// if the custom code is not 20000, it is judged as an error.
		if (res.code &&res.code !== 200) {
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
				// to re-login
				ElMessageBox.confirm('您已经退出, 可以继续停留在本页面, 也可以重新登录', '确定退出', {
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					//store.dispatch('user/resetToken').then(() => {
						//location.reload()
					//})
				})
			}  
			ElMessage({
				message: res.message || res.msg || 'Error',
				type: 'error',
				duration: 5 * 1000
			})
			return Promise.reject(new Error(res.message || res.msg || 'Error'))
		} else {
			//console.log(res)
			return res 
		} 
		/*
		if (code === '00000') {
			return response.data;
		} else {
			// 响应数据为二进制流处理(Excel导出)
			if (response.data instanceof ArrayBuffer) {
				return response;
			}

			ElMessage({
				message: msg || '系统出错',
				type: 'error'
			});
			return Promise.reject(new Error(msg || 'Error'));
		}
		*/
	},
	error => {  
		//console.log('error：' + error) // for debug
		var msg=error.response.status=="403"?"403错误,访问拒绝或无权限访问":(error.message||error.msg)
		ElMessage({
		  message:msg,
		  type: 'error',
		  duration: 5 * 1000
		})
		return Promise.reject(error)
		/*
		const { code, msg } = error.response.data;
		if (code === 'A0230') {
			// token 过期
			localStorage.clear(); // 清除浏览器全部缓存
			window.location.href = '/'; // 跳转登录页
			ElMessageBox.alert('当前页面已失效，请重新登录', '提示', {});
		} else {
			ElMessage({
				message: msg || '系统出错',
				type: 'error'
			});
		}
		return Promise.reject(new Error(msg || 'Error'));
		*/
	}
);

// 导出 axios 实例
export default service;
